import { PageContainer } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Button, message, Select, InputNumber, TreeSelect } from 'antd';
import { useNavigate } from 'react-router-dom';
import { createStyles } from 'antd-style';
import { apiAdd } from '@/services/system/apimanage';
import { resourceListTree } from '@/services/system/resource';
const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    background: '#f5f5f5',
    minHeight: 'calc(100vh - 48px)',
  },
  card: {
    borderRadius: '8px',
    boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03)',
  },
  form: {
    maxWidth: '800px',
    margin: '0 auto',
  },
  formItem: {
    marginBottom: '24px',
    '& .ant-form-item-label': {
      fontWeight: 500,
    },
  },
  buttonGroup: {
    display: 'flex',
    justifyContent: 'center',
    gap: '16px',
    marginTop: '40px',
  },
  formLayout: {
    display: 'grid',
    gridTemplateColumns: '1fr 1fr',
    gap: '24px',
  },
  fullWidth: {
    gridColumn: '1 / -1',
  },
}));

const ApiManageAdd: React.FC = () => {
  const { styles } = useStyles();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [resourceOptions, setResourceOptions] = useState<any[]>([]);

  useEffect(() => {
    const fetchResourceList = async () => {
      try {
        const response = await resourceListTree();
        if (response.code === 200) {
          // 递归处理树形数据
          // 添加一个根节点选项
          const rootNode = {
            title: '顶级资源',
            value: '0',
            key: '0',
            children: response.data,
          };
          setResourceOptions([rootNode]);

        } else {
          message.error(response.msg || '获取资源列表失败');
        }
      } catch (error) {
        console.error('获取资源列表失败:', error);
        message.error('获取资源列表失败');
      }
    };

    fetchResourceList();
  }, []);

  const onFinish = async (values: any) => {
    try {
      const response = await apiAdd(values);
      if (response.code === 200) {
        message.success('新增接口成功');
        navigate('/system/apimanage');
      } else {
        message.error(response.msg || '新增接口失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('新增接口失败');
    }
  };

  const handleCancel = () => {
    navigate('/system/apimanage');
  };

  return (
    <PageContainer>
      <div className={styles.container}>
        <Card className={styles.card}>
          <Form
            form={form}
            layout="vertical"
            onFinish={onFinish}
            className={styles.form}
          >
            <div className={styles.formLayout}>
            <Form.Item
                name="resourceId"
                label="上级资源"
                rules={[{ required: true, message: '请选择上级资源' }]}
                className={styles.formItem}
              >
                <TreeSelect
                  showSearch
                  style={{ width: '100%' }}
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  placeholder="请选择上级资源"
                  allowClear
                  treeDefaultExpandAll
                  treeData={resourceOptions}
                  fieldNames={{
                    label: 'resourceName',
                    value: 'id',
                    children: 'children',
                  }}
                  treeNodeFilterProp="resourceName"
                />
              </Form.Item>

              <Form.Item
                name="scopeName"
                label="接口名称"
                rules={[{ required: true, message: '请输入接口名称' }]}
                className={styles.formItem}
              >
                <Input placeholder="请输入接口名称" />
              </Form.Item>

              <Form.Item
                name="scopeType"
                label="接口类型"
                rules={[{ required: true, message: '请选择接口类型' }]}
                className={styles.formItem}
              >
                <Select placeholder="请选择接口类型">
                  <Select.Option value="1">GET</Select.Option>
                  <Select.Option value="2">POST</Select.Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="scopePath"
                label="接口地址"
                rules={[{ required: true, message: '请输入接口地址' }]}
                className={styles.formItem}
              >
                <Input placeholder="请输入接口地址，如：/sys/user/list" />
              </Form.Item>

              <Form.Item
                name="sort"
                label="排序"
                rules={[{ required: true, message: '请输入排序号' }]}
                className={styles.formItem}
              >
                <InputNumber
                  min={1}
                  max={999}
                  style={{ width: '100%' }}
                  placeholder="请输入排序号，数值越小越靠前"
                />
              </Form.Item>

              <Form.Item
                name="status"
                label="接口状态"
                rules={[{ required: true, message: '请选择接口状态' }]}
                className={styles.formItem}
              >
                <Select placeholder="请选择接口状态">
                  <Select.Option value={0}>正常</Select.Option>
                  <Select.Option value={1}>禁用</Select.Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="scopePermission"
                label="权限标识"
                rules={[{ required: true, message: '请输入权限标识' }]}
                className={styles.formItem}
              >
                <Input placeholder="请输入权限标识" />
              </Form.Item>

              <Form.Item
                name="remark"
                label="接口备注"
                className={`${styles.formItem} ${styles.fullWidth}`}
              >
                <Input.TextArea rows={4} placeholder="请输入接口备注" />
              </Form.Item>
            </div>

            <div className={styles.buttonGroup}>
              <Button onClick={handleCancel}>
                返回
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </div>
          </Form>
        </Card>
      </div>
    </PageContainer>
  );
};

export default ApiManageAdd;
